package cn.aitrox.ry.common.config;

import cn.aitrox.ry.bean.RespResult;
import com.fasterxml.jackson.databind.JavaType;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;

public class JsonMessageConverter extends MappingJackson2HttpMessageConverter {
    @Override
    public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

        JavaType javaType = getJavaType(type, contextClass);
        return this.getObjectMapper().readValue(inputMessage.getBody(), javaType);
    }

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

        if (object instanceof RespResult) {
            super.writeInternal(object, outputMessage);
        } else {
            String objectName = object.getClass().getName();
            if (objectName.contains("springfox") || (objectName.contains("ArrayList") && ((ArrayList) object).get(0).getClass().getName().contains("springfox"))) {
                super.writeInternal(object, outputMessage);
            } else {
                super.writeInternal(RespResult.ok(), outputMessage);
            }
        }

    }

}
